package com.fancon.rage.comic.vn.gui;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;

import com.fancon.android.cache.CacheImageView;
import com.fancon.android.multithread.RequestUI;
import com.fancon.rage.comic.vn.R;
import com.fancon.rage.comic.vn.activity.PhotoDetailActivity;
import com.fancon.rage.comic.vn.activity.RageBaseActivity;
import com.fancon.rage.comic.vn.activity.RageVietActivity;
import com.fancon.rage.comic.vn.apiservice.RageApiService;
import com.fancon.rage.comic.vn.entity.Photo;
import com.fancon.rage.comic.vn.local.db.RageSqlHelper;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * 
 * @author binhbt 2012 Pageview adapter
 */
public class PageViewAdapter extends PagerAdapter {
	private final static int NUM_PAGE = 50;
	private Activity mContext;
	private ArrayList<Photo> photos;
	private Paginator paginator;
	private PullToRefreshListView pullList;
	private int pages = 0;
	private int mode;

	@SuppressWarnings("unused")
	public PageViewAdapter(Activity context, ArrayList<Photo> photos,
			Paginator paginator, int mode) {
		mContext = context;
		this.photos = photos;
		this.paginator = paginator;
		this.mode = mode;
		// Add new page for paginator -- fuckin here
		paginator.removeAllChild();
		if (photos == null) {
			pages = 1;
		} else {
			int rages = photos.size();
			if (photos == null) {
				pages = 1;
			}
			if (rages % NUM_PAGE == 0) {
				pages = rages / NUM_PAGE;
			} else {
				pages = rages / NUM_PAGE + 1;
			}
			for (int i = 0; i < pages; i++) {
				paginator.addPage();
			}
			paginator.selectedPage(0);
		}
	}

	@Override
	public int getCount() {
		return pages;
	}

	public Object instantiateItem(View collection, int position) {

		LayoutInflater inflater = (LayoutInflater) collection.getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.page_item, null);
		pullList = (PullToRefreshListView) view
				.findViewById(R.id.rage_pull_list);
		ListView rageList = pullList.getRefreshableView();
		if (photos == null) {
			rageList.setDivider(null);
		}
		rageList.setCacheColorHint(0);
		RageListAdapter adapter = new RageListAdapter(mContext, photos,
				position);
		rageList.setAdapter(adapter);
		pullList.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				((IRefreshable) mContext).doRefresh(pullList);
			}
		});
		((ViewPager) collection).addView(view, 0);
		return view;
	}

	@Override
	public void destroyItem(View arg0, int arg1, Object arg2) {
		((ViewPager) arg0).removeView((View) arg2);
	}

	@Override
	public void finishUpdate(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == ((View) arg1);

	}

	@Override
	public void restoreState(Parcelable arg0, ClassLoader arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public Parcelable saveState() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void startUpdate(View arg0) {
		// TODO Auto-generated method stub

	}

	public class RageListAdapter extends BaseAdapter implements Filterable {
		private LayoutInflater mInflater;
		private Context context;
		private ArrayList<Photo> mRageItems;
		private int pageIndex;

		public RageListAdapter(Context context, ArrayList<Photo> rageItems,
				int index) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			this.context = context;
			this.mRageItems = rageItems;
			this.pageIndex = index;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (mRageItems == null) {
				convertView = mInflater.inflate(R.layout.no_data, null);
				return convertView;
			}
			Photo item = null;
			try {
				item = (Photo) mRageItems.get(position + NUM_PAGE * pageIndex);
			} catch (Exception e) {
				// TODO: handle exception
			}
			// final int a= position + NUM_PAGE * pageIndex;

			final Photo photo = item;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.rage_list_item, null);
				holder = new ViewHolder();
				holder.title = (TextView) convertView
						.findViewById(R.id.rage_title);
				holder.thumb = (CacheImageView) convertView
						.findViewById(R.id.rage_thumb);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// Log.d("position >>>", String.valueOf(a));
					// Log foot print user to db
					if (photo != null && photo.getId() != null) {
						LogFootPrintRequest fp = new LogFootPrintRequest(
								"fp_add", mContext, photo.getId().toString());
						// add photo to have read
						((RageVietActivity) mContext).getFootPrint().add(
								photo.getId().toString());
						((RageBaseActivity) mContext).getGlobalState()
								.getRequestQueue().addRequest(fp);
						TextView title = (TextView) v
								.findViewById(R.id.rage_title);
						title.setTypeface(null, Typeface.NORMAL);

						// v.setBackgroundResource(R.drawable.row_bg_black);
						Intent i = new Intent(mContext,
								PhotoDetailActivity.class);
						if (mode == TopControlView.EN_MODE) {
							i.putExtra("photoUrl", photo.getImageUrl());
						} else {
							i.putExtra("photoUrl", RageApiService.ROOT_API
									+ photo.getImageUrl());
						}
						mContext.startActivity(i);
					}
				}
			});
			if (item != null) {
				try {
					holder.title.setText(item.getTitle());
					if (mode == TopControlView.EN_MODE) {
						holder.thumb.loadImage(item.getThumbUrl(), true);
					} else {
						holder.thumb.loadImage(
								RageApiService.ROOT_API + item.getThumbUrl(),
								true);
					}
					// Check for item that read in last
					ArrayList<String> footPrint = ((RageVietActivity) mContext)
							.getFootPrint();
					if (footPrint != null) {
						if (footPrint.contains(item.getId().toString())) {
							holder.title.setTypeface(null, Typeface.NORMAL);
						} else {
							holder.title.setTypeface(null, Typeface.BOLD);
						}
					}

				} catch (Exception e) {
					// TODO: handle exception
				}
			}

			return convertView;
		}

		class ViewHolder {
			CacheImageView thumb;
			TextView title;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (mRageItems == null) {
				return 1;
			}
			if (pageIndex * NUM_PAGE < mRageItems.size()) {
				if (pages > 1) {
					return NUM_PAGE;
				}
				return mRageItems.size();
			}
			return mRageItems.size() - (pages - 1) * NUM_PAGE;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			// return this.mRageItems.get(arg0 + pageIndex*NUM_PAGE);
			return arg0;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

	}

	class LogFootPrintRequest extends RequestUI {
		private String photId;

		public LogFootPrintRequest(Object key, Activity activity,
				final String photoId) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			this.photId = photoId;
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			addFootPrint(this.photId);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub

		}

	}

	private void addFootPrint(String photoId) {
		RageSqlHelper sqlHelper = new RageSqlHelper(mContext);
		sqlHelper.openDataBase();
		if (!sqlHelper.isFPExist(photoId)) {
			sqlHelper.addFootPrint(photoId);
		}
		sqlHelper.close();
	}
}